package com.idea.relax.exception.api;


/**
 * @author: 沉香
 * @date: 2023/3/1
 * @description: 字符串format工具类
 */
public class StringFormatter {

	protected static final String EMPTY = "";

	protected static final String LEFT_BRACE = "{";

	protected static final String RIGHT_BRACE = "}";

	/**
	 * 同 log 格式的 format 规则
	 * <p>
	 *
	 * @param message   需要转换的字符串
	 * @param arguments 需要替换的变量
	 * @return 转换后的字符串
	 */
	public static String format(String message, Object... arguments) {
		// message 为 null 返回空字符串
		if (message == null) {
			return EMPTY;
		}
		// 参数为 null 或者为空
		if (arguments == null || arguments.length == 0) {
			return message;
		}
		StringBuilder sb = new StringBuilder((int) (message.length() * 1.5));
		int cursor = 0;
		int index = 0;
		int argsLength = arguments.length;
		for (int start, end; (start = message.indexOf(LEFT_BRACE, cursor)) != -1 && (end = message.indexOf(RIGHT_BRACE, start)) != -1 && index < argsLength; ) {
			sb.append(message, cursor, start);
			sb.append(arguments[index]);
			cursor = end + 1;
			index++;
		}
		sb.append(message.substring(cursor));
		return sb.toString();
	}

}
